package com.xxgc.zde.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxgc.zde.api.WechatLoginApi;
import com.xxgc.zde.api.response.WechatLoginResponse;
import com.xxgc.zde.controller.dto.UserLoginDTO;
import com.xxgc.zde.controller.vo.UserLoginVO;
import com.xxgc.zde.entity.UsersEntity;
import com.xxgc.zde.entity.UsersEntityRepository;
import com.xxgc.zde.service.UserLoginService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/* ResponseBody + Controller*/
@RestController
@RequestMapping("/login")
@Tag(name = "登录接口")
public class UserLoginController {
    @Resource
    private UserLoginService userLoginService;
    private static final String AppID = "wx2d058ff5b60d971b";

    private static final String AppSecret = "d81243980b5c04a4e13f9728ba316cb3";

    private UsersEntityRepository usersEntityRepository;

    @Autowired
    private WechatLoginApi wechatLoginApi;


    @Operation(summary = "测试通讯用")
    @GetMapping("/msg")
    public String msg(){
        return "成功编写了第一个接口";
    }

    @Operation(summary = "用户登录")
    @PostMapping("/userLogin/{code}")
    public UsersEntity userLogin(String openId,@PathVariable String code){
        WechatLoginResponse authorization_code = wechatLoginApi.getUserOpenId(AppID, AppSecret, code, "authorization_code");

        System.out.println("我的"+userLoginService.userLogin(authorization_code.getOpenid()));
        return userLoginService.userLogin(authorization_code.getOpenid());
    }


    @Operation(summary = "微信登录")
    @PostMapping("/wechatLogin/{code}")
    public String wechatLogin(@PathVariable String code){
//      System.out.println("code = " + code);
        WechatLoginResponse authorization_code = wechatLoginApi.getUserOpenId(AppID, AppSecret, code, "authorization_code");
        System.out.println("authorization_code = " + authorization_code);
        QueryWrapper<UsersEntity> qw=new QueryWrapper<>();
        qw.eq("open_id",authorization_code.getOpenid());
        UsersEntity one = usersEntityRepository.getOne(qw);
        if(one==null){
            one=new UsersEntity();
            one.setOpenId(authorization_code.getOpenid());
            boolean save = usersEntityRepository.save(one);
            return one.getId();
        }
        return one.getId();
    }
}
